library(readxl)
#No.1
#作用:根据输入文件的类型返回对应的数据矩阵
#' Title
#'
#' @param filePath
#' @param readColumnName
#' @param rowNamesIndex
#' @param quoteInput
#'
#' @return
#' @export
#'
#' @examples
fileProcess <- function(filePath,readColumnName=TRUE,rowNamesIndex=NULL,quoteInput=""){
  #Step1:通过正则过滤后缀，存入fileType变量中
  # str<-strsplit(filePath,"\\.")
  # fileType <- str[[1]][2]
  fileType <- sub('.*\\.', '', filePath)
  print(paste("filePath:",filePath))
  print(paste("readColumnName:",readColumnName))
  print(paste("rowNamesIndex:",rowNamesIndex))
  print(paste("fileType:",fileType))

  #Step2:通过后缀选择对应格式的读取方法
  if(tolower(fileType) == 'csv'){
    print("CSV processing")
    data <- read.csv(filePath,header = readColumnName,row.names=rowNamesIndex,check.names=FALSE)
    return(data)
  }
  if(tolower(fileType) == 'txt' | tolower(fileType) == 'tsv'){
    print("TXT or TSV processing")
    data <- read.csv(filePath,sep="\t",check.names=FALSE,header = readColumnName,row.names=rowNamesIndex,quote=quoteInput)
    # data <- read.table(filePath,sep="\t",header = readColumnName,row.names=rowNamesIndex,quote=quoteInput,check.names=FALSE)
    return(data)
  }
  if(tolower(fileType) == 'xls' | tolower(fileType) == 'xlsx'){
    print("XLS or XLSX processing")
    data <- readxl::read_excel(filePath, sheet=1,col_names = readColumnName)
    return(data)
  }
  return (NULL)
}

#No.2
#作用:把excel文件转化成csv文件
#' Title
#'
#' @param filePath
#' @param fileName
#'
#' @return
#' @export
#'
#' @examples
excel2csv <- function(filePath,fileName){
  data <- read_excel(filePath, sheet=1)
  write.csv(data, file = paste(json$outdir, "/",fileName,".csv", sep = ""), row.names = FALSE)
}

#No.3
#作用:判断输入的文件是否是excel类型
#' Title
#'
#' @param filePath
#'
#' @return
#' @export
#'
#' @examples
isExcel <- function(filePath){
  fileType <- sub('.*\\.', '', filePath)
  if(tolower(fileType) == 'xls' | tolower(fileType) == 'xlsx'){
    return(TRUE)
  }else{
    return(FALSE)
  }
  print("excel ---> csv  done......")
}

#No.4
#作用:# 尝试读取文件并检测分隔符
#' Title
#'
#' @param file
#'
#' @return
#' @export
#'
#' @examples
detect_delimiter <- function(file) {
  # 读取文件的前几行
  sample_lines <- readLines(file, n = 5)

  # 检测逗号分隔符
  comma_test <- tryCatch({
    df_comma <- read.csv(text = paste(sample_lines, collapse = "\n"), sep = ",")
    return("comma")
  }, error = function(e) {
    return(NULL)
  })

  # 检测分号分隔符
  semicolon_test <- tryCatch({
    df_semicolon <- read.csv(text = paste(sample_lines, collapse = "\n"), sep = ";")
    return("semicolon")
  }, error = function(e) {
    return(NULL)
  })

  # 返回检测结果
  if (!is.null(comma_test)) {
    return("comma")
  } else if (!is.null(semicolon_test)) {
    return("semicolon")
  } else {
    return("unknown")
  }
}

# 函数：依据padj和log2FoldChange，过滤DESeq2差异分析结果，得到过滤后的data.frame
#' Title
#'
#' @param DDS_result
#' @param max_padj
#' @param min_FC
#'
#' @return
#' @export
#'
#' @examples
Filter_DESeq2_Diff <- function(DDS_result, max_padj=NA, min_FC=NA){
  ##错误情况，没有任何一个阈值被输入
  if (is.na(max_padj) & is.na(min_FC)){
    stop("过滤需要至少一个阈值")
    ##padj为空，不过滤padj
  }else if (is.na(max_padj)){
    log2_min_FC <- log2(min_FC)
    DDS_result_filter <- subset(DDS_result, abs(log2FoldChange) > log2_min_FC)
    ##min_FC为空，不过滤FoldChange
  }else if (is.na(min_FC)){
    DDS_result_filter <- subset(DDS_result, padj < max_padj)
    ## 其它情况，先将FC阈值取log2，再过滤padj和log2FoldChange
  } else{
    log2_min_FC <- log2(min_FC)
    DDS_result_filter <- subset(DDS_result, padj < max_padj & abs(log2FoldChange) > log2_min_FC)
  }
  ## 返回过滤后的dataframe
  return(DDS_result_filter)
}

